package com.bwie.parkdemo.mvvm.viewmodel;

import android.app.Application;
import android.content.Intent;
import android.databinding.BaseObservable;
import android.databinding.Observable;
import android.databinding.ObservableField;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;

import com.blankj.utilcode.util.SPStaticUtils;
import com.bwie.lib_core.action.ActActionField;
import com.bwie.lib_core.base.BaseEntity;
import com.bwie.lib_core.mvvm.base.BaseViewModel;
import com.bwie.parkdemo.dao.LoginUserServe;
import com.bwie.parkdemo.mvc.MainActivity;
import com.bwie.parkdemo.mvvm.model.LoginModel;
import com.bwie.parkdemo.mvvm.model.entity.LoginEntity;
import com.bwie.parkdemo.mvvm.model.request_entity.UserEntity;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 用户登录界面的ViewModel
 * */
public class LoginViewModel extends BaseViewModel<LoginModel>  {

    //databinding下绑定用户名以及密码数据
    //由于当前viewmodel层只负责向xml中设置数据
    //无获取方法调用权限,所以需要databinding数据
    //双向绑定方式进行绑定,从而获取用户输入的数据
    private UserEntity entity;
    private LoginListener listener;//控件监听器
    private LoginUserServe dbServe;//用户本地缓存数据库操作工具服务

    public LoginViewModel(@NonNull Application application) {
        super(application);
        //调用userName以及userPwd设置初始数据用来显示
        entity = new UserEntity("zxy","123456");
        dbServe = new LoginUserServe(getApplication());//初始化用户本地缓存数据库操作工具服务
    }

    public UserEntity getEntity() {
        return entity;
    }

    @Override
    protected LoginModel createModel() {
        return new LoginModel();//构建具体发起网络请求model类
    }

    @Override
    protected void initData() {
    }

    public LoginListener getListener() {
        //初始化监听器对象
        if (listener == null)
            listener = new LoginListener();
        return listener;
    }

    //设计按钮监听->调用model层的网络请求->添加给databinding
    //用来触发按钮点击
    public class LoginListener{
        public void loginClick(){
            //具体发起网络请求
            Log.e("ZXY","LoginListener:"
                    +entity.getUserName()+"&&"+entity.getUserPwd());
            //配置网络请求参数
            /**
             * {
             *   "sign": "3a47ae5c0227d09d4ffcf22ccaa7b11e",
             *   "time": "1582523446",
             *   "uName": "zxy",
             *   "uPwd": "123456"
             * }
             * */
            //封装请求的JSON
            String requestJSON = "{\"uName\":\""+entity.getUserName()+"\"," +
                    "\"uPwd\":\""+entity.getUserPwd()+"\"," +
                    "\"time\":\""+(System.currentTimeMillis()/1000)+"\"}";
            //封装请求体
            RequestBody body = RequestBody.create(MediaType.parse("application/json"),requestJSON);
            m.request(body).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<BaseEntity>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            addCompositeDisposable(d);
                            showDialog();
                        }
                        @Override
                        public void onNext(BaseEntity entity) {
                            Log.e("ZXY","onNext已进入");
                            if (!entity.statuesCode.equals("200")){
                                showMsg("onNext:请求出错:"+entity.msg);
                                return;
                            }
                            //向下转型为对应的LoginUserEntity->请求返回的实体类
                            LoginEntity loginEntity = (LoginEntity) entity;
                            //保存token到sp存储中
                            SPStaticUtils.put("token",loginEntity.getLoginValues().token);
                            //保存homeurl->主页网址->记住用户登录状态时；从启屏页跳转到框架页时
                            //框架页需要显示h5页面
                            SPStaticUtils.put("home",loginEntity.getHome());
                            //保存用户信息到本地sqlite
                            int index = dbServe.insertUser(loginEntity.getLoginValues());
                            if (index <= 0)
                                showMsg("用户本地保存失败");
                            //跳转到软件框架页用来显示首页的h5
                            Bundle bundle = new Bundle();
                            bundle.putString(ActActionField.ACTBUNDLE,loginEntity.getHome());
                            Map<String,Object>map = new HashMap<>();
                            map.put(ActActionField.ACTCLAZZ, MainActivity.class);
                            map.put(ActActionField.ACTBUNDLE,bundle);
                            startAct(map);
                            finishAct();
                        }
                        @Override
                        public void onError(Throwable e) {
                            Log.e("ZXY","onError:"+e.getMessage());
                            showMsg("请求错误:"+e.getMessage());
                            disDialog();
                        }
                        @Override
                        public void onComplete() {
                            disDialog();
                        }
                    });
        }
    }


}
